package com.microtf.inscription.framework.service;

import com.microtf.inscription.framework.exception.BusinessException;
import com.microtf.inscription.framework.vo.blog.PostVo;
import com.microtf.inscription.jpa.BlogPostJpa;
import com.microtf.inscription.jpa.BlogSpaceJpa;
import com.microtf.inscription.jpa.BlogCategoryJpa;
import com.microtf.inscription.jpa.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolationException;
import java.util.*;

/**
 * 博客内容服务
 *
 * @author guliuzhong
 * @author guliuzhong
 * @version 1.0
 * @since 1.0
 */
@Service
@Slf4j
public class BlogService extends BaseService {
    final int shortContLen = 100;
    BlogPostJpa blogPostJpa;
    BlogSpaceJpa blogSpaceJpa;
    UserService userService;
    BlogCategoryJpa blogCategoryJpa;

    @Autowired
    public void setBlogJpa(BlogPostJpa blogPostJpa) {
        this.blogPostJpa = blogPostJpa;
    }

    @Autowired
    public void setBlogSpaceJpa(BlogSpaceJpa blogSpaceJpa) {
        this.blogSpaceJpa = blogSpaceJpa;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setCategoryJpa(BlogCategoryJpa blogCategoryJpa) {
        this.blogCategoryJpa = blogCategoryJpa;
    }

    public List<BlogSpace> getBlogSpace(Long userId) {
        User user = userService.getUser(userId);
        return blogSpaceJpa.findBlogSpaceByUser(user);
    }

    public Optional<BlogSpace> getBlogSpaceById(Integer blogId) {
        return blogSpaceJpa.findById(blogId);
    }

    public Page<BlogCategory> getAllCategory(BlogSpace blogSpace, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "categoryId")));
        return blogCategoryJpa.findByBlogSpace(blogSpace, pageRequest);
    }

    //    BaiduSpider baiduSpider;
//
//    BlogCommentJpa blogCommentJpa;
//    HtmlService htmlService;
//
//    UserService userService;
//
//    CategoryService categoryService;
//
//    @Autowired
//    public void setBaiduSpider(BaiduSpider baiduSpider) {
//        this.baiduSpider = baiduSpider;
//    }
//
//    @Autowired
//    public void setBlogJpa(BlogJpa blogJpa) {
//        this.blogJpa = blogJpa;
//    }
//
//    @Autowired
//    public void setBlogCommentJpa(BlogCommentJpa blogCommentJpa) {
//        this.blogCommentJpa = blogCommentJpa;
//    }
//
//    @Autowired
//    public void setHtmlService(HtmlService htmlService) {
//        this.htmlService = htmlService;
//    }
//
//    @Autowired
//    public void setUserService(UserService userService) {
//        this.userService = userService;
//    }
//
//    @Autowired
//    public void setCategoryService(CategoryService categoryService) {
//        this.categoryService = categoryService;
//    }
//
    public Page<BlogPost> getPostBySpaceAndUser(Integer pageIndex, Sort sort, Integer pageSize, BlogSpace blogSpace, User user) {
        pageIndex = (pageIndex == null) ? 1 : pageIndex;
        if (sort == null) {
            sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "postId"));
        }
        PageRequest request = PageRequest.of(pageIndex - 1, pageSize, sort);
        return blogPostJpa.findBlogPostByBlogSpaceAndAuthor(blogSpace, user, request);
    }

    public Page<BlogPost> getBlogList(Integer catId, Integer pageIndex, Sort sort, Integer pageSize) {
        pageIndex = (pageIndex == null) ? 1 : pageIndex;
        if (sort == null) {
            sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "postId"));
        }
        PageRequest request = PageRequest.of(pageIndex - 1, pageSize, sort);
        return blogPostJpa.findAll(request);
    }

    //
//    public Page<Blog> getCatBlogList(List<Category> categories, Integer pageIndex, Sort sort, Integer pageSize) {
//        pageIndex = (pageIndex == null) ? 1 : pageIndex;
//        if (sort == null) {
//            sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "postId"));
//        }
//        PageRequest request = PageRequest.of(pageIndex - 1, pageSize, sort);
//        return blogJpa.findAllByBlogCategoryIn(categories, request);
//    }
//
    public Optional<BlogPost> getBlogPost(Integer postId) {
        return blogPostJpa.findById(postId);
    }

    public void deleteBlog(Integer postId) {
        Optional<BlogPost> byId = blogPostJpa.findById(postId);
        byId.ifPresent(blogPost -> {
            blogPost.getBlogComments().forEach(item -> item.setAuthor(null));
            blogPost.setCategories(null);
            blogPost.setAuthor(null);
            blogPost.setBlogSpace(null);
            blogPostJpa.delete(blogPost);
        });
    }

    //
    public Optional<BlogPost> getBlog(Integer postId) {
        if (postId == null) {
            return Optional.empty();
        }
        return blogPostJpa.findById(postId);
    }

    //
    public BlogPost save(PostVo postVo) throws ConstraintViolationException {
        validatePojoAndThrow(postVo);
//        String contentText = htmlService.filterNone(blogPojo.getCont());
//        List<String> keywords = HanLP.extractKeyword(contentText, 15);
//        String summary = HanLP.getSummary(contentText, 255);
//        if (contentText.length() > shortContLen) {
//            contentText = contentText.substring(0, shortContLen);
//        }

        Optional<BlogPost> blogOptional = getBlog(postVo.getPostId());
        BlogPost blogPost = blogOptional.orElseGet(BlogPost::new);

        BlogSpace blogSpace;
        if (blogPost.getPostId() == null) {
            if (postVo.getCreateDate() == null) {
                blogPost.setDateCreated(new Date());
            } else {
                blogPost.setDateCreated(postVo.getCreateDate());
            }
            Optional<BlogSpace> blogSpaceOptional = this.getBlogSpace(postVo.getAuthorId()).stream().filter(item -> item.getSpaceId().equals(postVo.getBlogSpaceId())).findFirst();
            if (!blogSpaceOptional.isPresent()) {
                throw new BusinessException("博客空间不存在。");
            }
            blogSpace=blogSpaceOptional.get();
            blogPost.setBlogSpace(blogSpace);
            User user = userService.getUser(postVo.getAuthorId());
            if (user == null) {
                throw new BusinessException("操作用户不合法。");
            }
            blogPost.setAuthor(user);
        }else{
            blogSpace=blogPost.getBlogSpace();
        }

        if (!blogPost.getAuthor().getId().equals(postVo.getAuthorId())) {
            throw new BusinessException("你无权在此博客发布内容。用户名不正确");
        }


        blogPost.setTitle(postVo.getTitle());
        if (blogPost.getBlogPostCont() == null) {
            BlogPostCont blogPostCont = new BlogPostCont();
            blogPostCont.setCont(postVo.getCont());
            blogPost.setBlogPostCont(blogPostCont);
        } else {
            blogPost.getBlogPostCont().setCont(postVo.getCont());
        }

//        blogPost.setu(contentText);
//        if(blogPojo.getPostId() && blogPojo.getUser().getUserId())
//        List<BlogCategory> blogCategoriesByBlogSpaceAndTitleIn = blogCategoryJpa.findBlogCategoriesByBlogSpaceAndTitleIn(blogSpaceOptional.get(), Arrays.asList(postVo.getCatNames()));
        blogPost.setCategories(blogCategoryJpa.findBlogCategoriesByBlogSpaceAndTitleIn(blogSpace, Arrays.asList(postVo.getCatNames())));
        blogPost.setState(postVo.getState() != null ? postVo.getState() : "draft");
//        blogPost.setSummary(summary);
//        blogPost.setKeywords(keywords.stream().collect(Collectors.joining(",")).toString());
        BlogPost save = blogPostJpa.save(blogPost);
//        if (save.getState() != null && "publish".equalsIgnoreCase(save.getState())) {
//            pushToBaidu(save);
//        }
        return save;
    }
//
//    public void pushToBaidu(Blog blog) {
//        SiteSettingVo siteSetting = getSiteSetting();
//        Collection<String> pushUrl = new ArrayList<>();
//        String link=siteSetting.getMainUrl()+"/blog/view/"+blog.getPostId();
//        log.info("当前推送地址{}",link);
//        pushUrl.add(link);
//        baiduSpider.pushUrlToSpider(pushUrl);
//    }
//
//    public Page<BlogComment> getBlogComment(Blog blog, Integer pageIndex, Sort sort, Integer pageSize) {
//        pageIndex = (pageIndex == null) ? 1 : pageIndex;
//        if (sort == null) {
//            sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
//        }
//        PageRequest request = PageRequest.of(pageIndex - 1, pageSize, sort);
//        return blogCommentJpa.findByBlog(blog, request);
//    }
//
//    public BlogComment saveComment(BlogComment blogComment) {
//        String contentText = htmlService.filterSimpleText(blogComment.getCont());
//        blogComment.setCont(contentText);
//        if (blogComment.getCreateDate() == null) {
//            blogComment.setCreateDate(new Date());
//        }
//        return blogCommentJpa.save(blogComment);
//    }
}
